package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.PointCheckDeviceDetailVO;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.PointCheckDeviceDetailMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PointCheckDeviceDetailServiceImpl implements IPointCheckDeviceDetailService {

    @Autowired
    private PointCheckDeviceDetailMapper pointCheckDeviceDetailMapper;
    @Autowired
    private IPointCheckDescriptionService pointCheckDescriptionService;
    @Autowired
    private IPointCheckTaskDealService pointCheckTaskDealService;
    @Autowired
    private IPointCheckTaskDeviceService pointCheckTaskDeviceService;
    @Autowired
    private IPointCheckTaskService pointCheckTaskService;

    @Override
    @UserDataIsolation(tableAlias = "t1")
    public List<PointCheckDeviceDetail> queryList(PointCheckDeviceDetail pointCheckDeviceDetail) {
        List<PointCheckDeviceDetail> deviceDetails = pointCheckDeviceDetailMapper.queryList(pointCheckDeviceDetail);
        if (CollUtil.isEmpty(deviceDetails)) {
            return new ArrayList<>();
        }
        deviceDetails.forEach(a -> {
            if (a.getDealId() != null) {
                a.setDeal(true);
            }

        });
        return deviceDetails;
    }
    @Override
    @UserDataIsolation(tableAlias = "t1")
    public Map<String,Object> queryListAbnormalList(Integer deviceId) {
        Map<String,Object> abnorma = new HashMap<>();
        PointCheckTaskDevice pointCheckTaskDevice = new PointCheckTaskDevice();
        pointCheckTaskDevice.setDeviceId(deviceId);

        List<PointCheckDeviceDetail> deviceDetails = pointCheckDeviceDetailMapper.queryListAbnormalList(pointCheckTaskDevice);
        LinkedHashMap<String, List<PointCheckDeviceDetail>> typeMap = deviceDetails.stream().collect(Collectors.groupingBy(PointCheckDeviceDetail::getItem, LinkedHashMap::new, Collectors.toList()));
        Integer max = 0;
        ArrayList<Map<String,String>> list = new ArrayList<>();
        for (Map.Entry<String, List<PointCheckDeviceDetail>> typeEntry : typeMap.entrySet()) {
            if(typeEntry.getValue().size()>max){
                max = typeEntry.getValue().size();
            }

        }
        for (Map.Entry<String, List<PointCheckDeviceDetail>> typeEntry : typeMap.entrySet()) {
            if(typeEntry.getValue().size()==max){
                LinkedHashMap<String, String> map = new LinkedHashMap<>();
                map.put("type",typeEntry.getValue().get(0).getType());
                map.put("item",typeEntry.getKey());
                list.add(map);
            }
        }


        abnorma.put("number",deviceDetails.size());
        abnorma.put("max",max);
        abnorma.put("list",list);
        return abnorma;
    }



    @Override
    public Map<String, PointCheckDeviceDetailVO> getDeviceDetailVO(Integer taskDeviceId) {
        PointCheckDeviceDetail pointCheckDeviceDetail = new PointCheckDeviceDetail();
        pointCheckDeviceDetail.setTaskDeviceId(taskDeviceId);
        List<PointCheckDeviceDetail> deviceDetails = pointCheckDeviceDetailMapper.queryList(pointCheckDeviceDetail);
        if (CollUtil.isEmpty(deviceDetails)) {
//            return new HashMap<>();
            throw new CustomException("该产品型号下未添加自定义表单数据");
        }
        LinkedHashMap<String, List<PointCheckDeviceDetail>> queryMap = deviceDetails.stream().collect(Collectors.groupingBy(PointCheckDeviceDetail::getType, LinkedHashMap::new, Collectors.toList()));
//        Map<String, List<PointCheckDeviceDetail>> queryMap = deviceDetails.stream().collect(Collectors.groupingBy(PointCheckDeviceDetail::getType));
        LinkedHashMap<String, PointCheckDeviceDetailVO> result = new LinkedHashMap<>();
        for (Map.Entry<String, List<PointCheckDeviceDetail>> entry : queryMap.entrySet()) {
            String key = entry.getKey();
            List<PointCheckDeviceDetail> value = entry.getValue();
            PointCheckDeviceDetailVO detailVO = new PointCheckDeviceDetailVO();
            detailVO.setPointCheckDeviceDetails(value);
            //需要检查项
            List<PointCheckDeviceDetail> needCheckDetail = value.stream().filter(a -> StrUtil.isBlank(a.getStatus())).collect(Collectors.toList());
            //异常检查项
            List<PointCheckDeviceDetail> abnormalDetail = value.stream().filter(a -> StrUtil.equals(a.getStatus(), "异常")).collect(Collectors.toList());
            //正常检查项
            List<PointCheckDeviceDetail> normalDetail = value.stream().filter(a -> StrUtil.equals(a.getStatus(), "正常")).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(needCheckDetail)) {
                detailVO.setNeedCheckNum(needCheckDetail.size());
            } else {
                detailVO.setNeedCheckNum(0);
            }
            if (CollUtil.isNotEmpty(abnormalDetail)) {
                detailVO.setAbnormalNum(abnormalDetail.size());
            } else {
                detailVO.setAbnormalNum(0);
            }
            if (CollUtil.isNotEmpty(normalDetail)) {
                detailVO.setNormalNum(normalDetail.size());
            } else {
                detailVO.setNormalNum(0);
            }
            result.put(key, detailVO);
        }
        return result;
    }
    @Override
    public List<Map<String, Object>> getDeviceDetailVOV2(Integer taskDeviceId) {
        PointCheckDeviceDetail pointCheckDeviceDetail = new PointCheckDeviceDetail();
        pointCheckDeviceDetail.setTaskDeviceId(taskDeviceId);
        List<PointCheckDeviceDetail> deviceDetails = pointCheckDeviceDetailMapper.queryList(pointCheckDeviceDetail);
        if (CollUtil.isEmpty(deviceDetails)) {
//            return new HashMap<>();
            throw new CustomException("该产品型号下未添加自定义表单数据");
        }
        LinkedHashMap<String, List<PointCheckDeviceDetail>> queryMap = deviceDetails.stream().collect(Collectors.groupingBy(PointCheckDeviceDetail::getType, LinkedHashMap::new, Collectors.toList()));


        List<Map<String, Object>> typeEnum = new ArrayList<>();
        for (Map.Entry<String, List<PointCheckDeviceDetail>> entry : queryMap.entrySet()) {
            HashMap<String, Object> map = new HashMap<>();
            String key = entry.getKey();
            List<PointCheckDeviceDetail> value = entry.getValue();
            map.put("name",key);
            map.put("category",value.get(0).getCategory());

            ArrayList<String> childData = new ArrayList<>();
            for (PointCheckDeviceDetail p:value
                 ) {
                childData.add(p.getItem());
            }
            map.put("childData",childData);
            typeEnum.add(map);
        }
        return typeEnum;
    }

    @Override
    public Map<String, Object> getDeviceItemEnum(QueryVo queryVo) {
        Integer taskDeviceId = queryVo.filters.getInteger("task_device_id");
        Long companyId = queryVo.filters.getLong("company_id");

        return null;
    }

    @Override
    @UserDataIsolation
    public PointCheckDeviceDetail getOne(PointCheckDeviceDetail pointCheckDeviceDetail) {
        return pointCheckDeviceDetailMapper.getOne(pointCheckDeviceDetail);
    }

    @Override
    public Boolean add(PointCheckDeviceDetail pointCheckDeviceDetail, List<DevicePointCheckConfig> childData) {
        Boolean flag = pointCheckDeviceDetailMapper.add(pointCheckDeviceDetail) > 0;
        if (flag) {
            if (CollUtil.isEmpty(childData)){
                return true;
            }
            if (childData.size() == 1 && StrUtil.isBlank(childData.get(0).getField())){
                return true;
            }
            List<PointCheckDescription> descriptions = new ArrayList<>();
            for (DevicePointCheckConfig checkConfig : childData) {
                PointCheckDescription description = new PointCheckDescription();
                description.setDetailId(pointCheckDeviceDetail.getId());
                description.setField(checkConfig.getField());
                description.setDataType(checkConfig.getDataType());
                description.setOrderNum(checkConfig.getOrderNum());
                description.setCompanyId(pointCheckDeviceDetail.getCompanyId());
                description.setCreateTime(new Date());
                description.setDetail(checkConfig.getDetail());
                descriptions.add(description);
            }
            pointCheckDescriptionService.addBatch(descriptions);
        }
        return flag;
    }

    @Override
    @Transactional
    @UserDataIsolation
    public Boolean update(PointCheckDeviceDetail pointCheckDeviceDetail) {
        Integer id = pointCheckDeviceDetail.getId();
        PointCheckDeviceDetail param = new PointCheckDeviceDetail();
        param.setId(id);
        PointCheckDeviceDetail detail = getOne(param);
        if (detail == null) {
            throw new CustomException("没有查询到对应的检查项");
        }
        if (!StrUtil.equals(pointCheckDeviceDetail.getStatus(), detail.getStatus())) {
            pointCheckDeviceDetail.setCreateTime(new Date());
        }
        Boolean flag = pointCheckDeviceDetailMapper.update(pointCheckDeviceDetail) > 0;
        if (flag) {
            //点检任务状态的修改（将未开始状态修改为进行中）
            Integer taskDeviceId = pointCheckDeviceDetail.getTaskDeviceId();
            PointCheckTaskDevice pointCheckTaskDevice = new PointCheckTaskDevice();
            pointCheckTaskDevice.setId(taskDeviceId);
            PointCheckTask task = pointCheckTaskDeviceService.queryTask(pointCheckTaskDevice);
            if (task != null && StrUtil.equals(task.getStatus(), "0")) {
                PointCheckTask updateTask = new PointCheckTask();
                updateTask.setId(task.getId());
                updateTask.setStatus("1");
                pointCheckTaskService.update(updateTask);
            }
            if (StrUtil.equals(pointCheckDeviceDetail.getStatus(), "正常")) {
                //正常状态下，删除处理方式和文字描述
                PointCheckTaskDeal pointCheckTaskDeal = new PointCheckTaskDeal();
                pointCheckTaskDeal.setDetailId(pointCheckDeviceDetail.getId());
                pointCheckTaskDealService.delete(pointCheckTaskDeal);

                PointCheckDescription pointCheckDescription = new PointCheckDescription();
                pointCheckDescription.setDetailId(pointCheckDeviceDetail.getId());
                pointCheckDescriptionService.update(pointCheckDescription);
            }
        }
        return flag;
    }

    @Override
    @UserDataIsolation
    public Boolean delete(PointCheckDeviceDetail pointCheckDeviceDetail) {
        return pointCheckDeviceDetailMapper.delete(pointCheckDeviceDetail) > 0;
    }

    @Override
    @UserDataIsolation
    public void checkIsExist(PointCheckDeviceDetail pointCheckDeviceDetail) {
        PointCheckDeviceDetail result = pointCheckDeviceDetailMapper.checkIsExist(pointCheckDeviceDetail);
        if (result == null) {
            return;
        }
        if (pointCheckDeviceDetail.getId() == null || pointCheckDeviceDetail.getId().compareTo(result.getId()) != 0) {
            throw new CustomException("该任务下的检查类别下的检查项已存在");
        }
    }

//    /**
//     * 初始化产品检查信息
//     *
//     * @return
//     */
//    Map<String, PointCheckDeviceDetailVO> initDeviceDetailVO(Integer taskDeviceId) {
//        PointCheckTaskDevice taskDevice = new PointCheckTaskDevice();
//        taskDevice.setId(taskDeviceId);
//        PointCheckTaskDevice pointCheckTaskDevice = pointCheckTaskDeviceService.getOne(taskDevice);
//        Integer productId = pointCheckTaskDevice.getProductId();
//        QueryVo queryVo = new QueryVo();
//        queryVo.filters.put("product_id",productId);
//        List<ProductPointCheckConfig> productPointCheckConfigs = productPointCheckConfigService.queryPageList(queryVo);
//        if (CollUtil.isEmpty(productPointCheckConfigs)){
//            throw new CustomException("该产品型号还未自定义点检表单");
//        }
//        Map<String, List<ProductPointCheckConfig>> collect = productPointCheckConfigs.stream().collect(Collectors.groupingBy(ProductPointCheckConfig::getType));
//        Map<String, PointCheckDeviceDetailVO> result = new HashMap<>();
//        for (Map.Entry<String, List<ProductPointCheckConfig>> entry : collect.entrySet()) {
//            String key = entry.getKey();
//            List<ProductPointCheckConfig> value = entry.getValue();
//            PointCheckDeviceDetailVO detailVO = new PointCheckDeviceDetailVO();
//            detailVO.setNormalNum(0);
//            detailVO.setAbnormalNum(0);
//            detailVO.setNeedCheckNum(value.size());
//            //本文输入配置
//            List<ProductPointCheckConfig> textConfig = value.stream().filter(a -> StrUtil.equals("string", a.getDataType())).collect(Collectors.toList());
//            if (CollUtil.isEmpty(textConfig)){
//                detailVO.setTextItem(new ArrayList<>());
//            }else {
//                List<String> textList = new ArrayList<>();
//                for (ProductPointCheckConfig checkConfig : textConfig) {
//                    textList.add(checkConfig.getItem());
//                }
//                detailVO.setTextItem(textList);
//            }
//            detailVO.setPointCheckDeviceDetails(new ArrayList<>());
//            result.put(key, detailVO);
//        }
//        return result;
//    }
}
